package com.beemans.admob.demo.ui.fragments

import android.util.Log
import com.beemans.common.ui.fragments.CommonFragment
import com.beemans.common.utils.ToastUtils
import com.beemans.admob.ads.AbAdvertManager
import com.beemans.admob.ads.AbBannerAdvert
import com.beemans.admob.ads.AbBannerAdvertCallback
import com.beemans.admob.ads.AbBannerAdvertConfig
import com.beemans.admob.demo.R
import com.beemans.admob.demo.constant.Constant
import com.beemans.admob.demo.databinding.FragmentBannerAdBinding
import com.google.android.gms.ads.ResponseInfo
import com.tiamosu.databinding.delegate.lazyDataBindingOrNull
import com.tiamosu.databinding.page.DataBindingConfig
import com.tiamosu.fly.ext.clickNoRepeat

/**
 * @author tiamosu
 * @date 2020/7/8.
 */
class BannerAdFragment : CommonFragment() {
    private val dataBinding: FragmentBannerAdBinding? by lazyDataBindingOrNull { }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.fragment_banner_ad)
    }

    override fun initEvent() {
        //加载广告并展示
        dataBinding?.bannerAdBtnShow?.clickNoRepeat {
            showAdvert()
        }
    }

    /**
     * 展示广告
     */
    private fun showAdvert() {
        val flContainer = dataBinding?.bannerAdFlAd ?: return
        val advertConfig = AbBannerAdvertConfig(Constant.BANNER_ID)
        advertConfig.isCollapsible = true

        AbAdvertManager.loadBannerAdvert(
            this,
            flContainer,
            advertConfig,
            object : AbBannerAdvertCallback() {
                override fun onAdvertLoaded(bannerAdvert: AbBannerAdvert) {
                    printLog("广告加载成功")
                }

                override fun onAdvertLoadFail(bannerAdvert: AbBannerAdvert, adError: String?) {
                    printLog("广告加载失败 --- adError:$adError")
                }

                override fun onAdvertShow(
                    bannerAdvert: AbBannerAdvert,
                    responseInfo: ResponseInfo?
                ) {
                    printLog("广告展示 --- responseInfo:$responseInfo")
                }

                override fun onAdvertClicked(
                    bannerAdvert: AbBannerAdvert,
                    responseInfo: ResponseInfo?
                ) {
                    printLog("广告点击 --- responseInfo:$responseInfo")
                }

                override fun onAdvertClose(
                    bannerAdvert: AbBannerAdvert,
                    responseInfo: ResponseInfo?
                ) {
                    printLog("广告关闭 --- responseInfo:$responseInfo")
                }
            }
        )
    }

    private fun printLog(msg: String) {
        Log.e("susu", msg)
        ToastUtils.showShort(msg)
    }

    override fun doBusiness() {
    }
}